import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useExamStore } from '@/stores/modules/exam-student'

/**
 * 考试监控相关功能
 * @param {Object} settings 监控设置参数
 * @returns {Object} 监控相关方法
 */
export function useExamMonitor(settings) {
  const router = useRouter()
  const examStore = useExamStore()
  
  // 违规警告次数
  const warningCount = ref(0)
  // 最大警告次数（超过将强制提交）
  const maxWarnings = ref(settings.maxWarnings || 3)
  
  /**
   * 切屏检测
   * 监听页面可见性变化，记录切屏违规行为
   */
  const handleVisibilityChange = async () => {
    // 仅当页面不可见时触发（切换到其他窗口或标签页）
    if (!document.hidden) return

    // 如果不允许切屏
    if (!settings.allowSwitchScreen) {
      // 记录切屏违规
      const shouldForceSubmit = await examStore.recordViolation('switch_screen', '切换到其他窗口')
      
      warningCount.value++
      
      // 是否应该强制提交
      if (shouldForceSubmit || warningCount.value >= maxWarnings.value) {
        await handleForceSubmit('切屏次数过多')
      } else {
        ElMessage.warning(`切换窗口将被记录为违规行为，这是第 ${warningCount.value}/${maxWarnings.value} 次警告`)
      }
    } 
    // 如果限制切屏次数
    else if (settings.maxSwitchCount) {
      // 记录切屏违规
      const shouldForceSubmit = await examStore.recordViolation('switchScreen', '切换到其他窗口')
      
      // 计算剩余可切屏次数
      const remaining = settings.maxSwitchCount - examStore.switchScreenCount.value
      
      // 是否应该强制提交
      if (shouldForceSubmit || remaining <= 0) {
        await handleForceSubmit('切屏次数已用完')
      } else {
        ElMessage.warning(`您还可以切换窗口 ${remaining} 次`)
      }
    }
  }

  /**
   * 全屏控制
   * 监听全屏状态变化，记录退出全屏违规行为
   */
  const handleFullscreenChange = async () => {
    const isFullscreen = !!document.fullscreenElement
    examStore.setFullscreen(isFullscreen)

    // 如果要求全屏且当前不是全屏状态
    if (settings.requireFullscreen && !isFullscreen) {
      // 记录退出全屏违规
      const shouldForceSubmit = await examStore.recordViolation('exit_fullscreen', '退出全屏模式')
      
      warningCount.value++
      
      // 是否应该强制提交
      if (shouldForceSubmit || warningCount.value >= maxWarnings.value) {
        await handleForceSubmit('退出全屏次数过多')
      } else {
        ElMessage.warning(`请保持全屏状态，这是第 ${warningCount.value}/${maxWarnings.value} 次警告`)
        // 自动请求回到全屏
        requestFullscreen()
      }
    }
  }

  /**
   * 复制粘贴限制
   * 禁止复制粘贴，记录违规行为
   * @param {Event} event 事件对象
   */
  const handleCopyPaste = async (event) => {
    // 如果不允许复制粘贴
    if (!settings.allowCopyPaste) {
      // 阻止默认行为
      event.preventDefault()
      
      // 记录复制粘贴违规
      const shouldForceSubmit = await examStore.recordViolation('copyPaste', 
        `${event.type === 'copy' ? '复制' : '粘贴'}操作`)
      
      warningCount.value++
      
      // 是否应该强制提交
      if (shouldForceSubmit || warningCount.value >= maxWarnings.value) {
        await handleForceSubmit('复制粘贴违规次数过多')
      } else {
        ElMessage.warning(`禁止复制粘贴，这是第 ${warningCount.value}/${maxWarnings.value} 次警告`)
      }
    }
  }
  
  /**
   * 监控键盘快捷键
   * 禁止特定键盘快捷键（如打印、开发者工具等）
   * @param {KeyboardEvent} event 键盘事件
   */
  const handleKeyDown = async (event) => {
    // 监控常见的违规快捷键
    const blockedKeys = [
      // 禁止 F12 (开发者工具)
      { key: 'F12', ctrl: false, alt: false, shift: false },
      // 禁止 Ctrl+Shift+I (开发者工具)
      { key: 'I', ctrl: true, alt: false, shift: true },
      // 禁止 Ctrl+P (打印)
      { key: 'P', ctrl: true, alt: false, shift: false }
    ]
    
    // 检查是否匹配被禁止的快捷键
    const isBlocked = blockedKeys.some(k => 
      event.key === k.key && 
      event.ctrlKey === k.ctrl && 
      event.altKey === k.alt && 
      event.shiftKey === k.shift
    )
    
    if (isBlocked) {
      // 阻止默认行为
      event.preventDefault()
      
      // 记录键盘快捷键违规
      const shouldForceSubmit = await examStore.recordViolation('keyboardShortcut', 
        `使用快捷键: ${event.ctrlKey ? 'Ctrl+' : ''}${event.altKey ? 'Alt+' : ''}${event.shiftKey ? 'Shift+' : ''}${event.key}`)
      
      warningCount.value++
      
      // 是否应该强制提交
      if (shouldForceSubmit || warningCount.value >= maxWarnings.value) {
        await handleForceSubmit('违规使用快捷键次数过多')
      } else {
        ElMessage.warning(`禁止使用此快捷键，这是第 ${warningCount.value}/${maxWarnings.value} 次警告`)
      }
    }
  }

  /**
   * 强制提交
   * 违规次数过多时，强制提交试卷
   * @param {String} reason 强制提交的原因
   */
  const handleForceSubmit = async (reason = '违规次数过多') => {
    await ElMessageBox.alert(
      `由于${reason}，系统将自动提交您的试卷`,
      '警告',
      {
        type: 'warning',
        showClose: false,
        confirmButtonText: '确定'
      }
    )
    
    // 同步答案
    await examStore.syncAnswers()
    
    // 跳转到提交页面
    router.push(`/exam/${examStore.currentExam.id}/submit?force=true&studentPaperId=${examStore.currentExam.studentPaperId}`)
  }

  /**
   * 请求全屏
   */
  const requestFullscreen = async () => {
    try {
      await document.documentElement.requestFullscreen()
    } catch (error) {
      console.error('进入全屏失败:', error)
      ElMessage.error('无法进入全屏模式，请检查浏览器设置')
    }
  }
  
  /**
   * 初始化监控
   */
  const initMonitor = () => {
    // 如果要求全屏，请求全屏
    if (settings.requireFullscreen) {
      requestFullscreen()
    }
  }

  onMounted(() => {
    // 添加监听器
    document.addEventListener('visibilitychange', handleVisibilityChange)
    document.addEventListener('fullscreenchange', handleFullscreenChange)
    document.addEventListener('copy', handleCopyPaste)
    document.addEventListener('paste', handleCopyPaste)
    document.addEventListener('keydown', handleKeyDown)
    
    // 初始化监控
    initMonitor()
  })

  onUnmounted(() => {
    // 移除监听器
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    document.removeEventListener('fullscreenchange', handleFullscreenChange)
    document.removeEventListener('copy', handleCopyPaste)
    document.removeEventListener('paste', handleCopyPaste)
    document.removeEventListener('keydown', handleKeyDown)

    // 退出全屏状态
    if (document.fullscreenElement) {
      document.exitFullscreen().catch(err => console.error('退出全屏失败:', err))
    }
  })

  return {
    requestFullscreen,
    warningCount,
    maxWarnings,
    initMonitor
  }
}